<template>
  <a-modal title="修改菜单" v-model="show" :maskClosable="false" :width="1050" placement="right" :closable="true"
    @cancel="onClose" :footer="null" :visiable="orgEditVisiable">
    <a-form :form="form">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='法人行号' v-bind="formItemLayout">
            <a-input v-decorator="['instId']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="创建机构号" v-bind="formItemLayout" :validateStatus="validateStatus" :help="help"
            style="display: none">
            <a-input v-decorator="['crtOrgId']" />
            <a-input v-decorator="['id']" />
            <a-input v-decorator="['orgStatus']" />
            <a-input v-decorator="['oprId']" />
            <a-input v-decorator="['createTime']" />
            <a-input v-decorator="['lastOprId']" />
            <a-input v-decorator="['lastUpdateTime']" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构类型' v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%"
              v-decorator="['orgType', { rules: [{ required: true, message: '请选择机构类型' }] }]" :disabled="true">
              <a-select-option key="00">银行机构</a-select-option>
              <a-select-option key="01">代理机构虚拟机构</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构级别' v-bind="formItemLayout">
            <a-select mode="default" :allowClear="true" style="width: 100%" @change="handleOrglevelChange"
              v-decorator="['orgLevel', { rules: [{ required: true, message: '请选择机构级别' }] }]">
              <a-select-option key="00">总行</a-select-option>
              <a-select-option key="01">分行</a-select-option>
              <a-select-option key="02">支行</a-select-option>
              <a-select-option key="03">营业部/网点</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构编码' v-bind="formItemLayout">
            <a-input v-decorator="['orgCode',
            {
              rules: [
                { required: true, message: '机构编码不能为空' },
                { max: 20, message: '长度不能超过20个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构名称' v-bind="formItemLayout">
            <a-input v-decorator="['orgName',
            {
              rules: [
                { required: true, message: '机构名称不能为空' },
                { max: 100, message: '长度不能超过100个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='联行号' v-bind="formItemLayout">
            <a-input v-decorator="['bankBranchCode',
            {
              rules: [
                { required: true, message: '联行号不能为空' },
                { max: 14, message: '长度不能超过14个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='内部银行代码' v-bind="formItemLayout">
            <a-input v-decorator="['innerBankCode',
            {
              rules: [
                { required: true, message: '内部银行代码不能为空' },
                { max: 20, message: '长度不能超过20个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='机构联系人' v-bind="formItemLayout">
            <a-input v-decorator="['contactName',
            {
              rules: [
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人地址' v-bind="formItemLayout">
            <a-input v-decorator="['contactAddress',
            {
              rules: [
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人传真' v-bind="formItemLayout">
            <a-input v-decorator="['contactFax',
            {
              rules: [
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人电话' v-bind="formItemLayout">
            <a-input v-decorator="['contactPhone',
            {
              rules: [
                { max: 50, message: '长度不能超过50个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人邮编' v-bind="formItemLayout">
            <a-input v-decorator="['contactZipCode',
            {
              rules: [
                { max: 6, message: '长度不能超过6个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='联系人邮箱' v-bind="formItemLayout">
            <a-input v-decorator="['contactMail',
            {
              rules: [
                { max: 40, message: '长度不能超过40个字符' }
              ]
            }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='所属一级机构' v-bind="formItemLayout">
            <a-input v-decorator="['firstOrgCode']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='所属二级机构' v-bind="formItemLayout">
            <a-input v-decorator="['secondOrgCode']" :disabled="true" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='所属三级机构' v-bind="formItemLayout">
            <a-input v-decorator="['threeOrgCode']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='所属四级机构' v-bind="formItemLayout">
            <a-input v-decorator="['fourOrgCode']" :disabled="true" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='所属五级机构' v-bind="formItemLayout">
            <a-input v-decorator="['fiveOrgCode']" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label='所属六级机构' v-bind="formItemLayout">
            <a-input v-decorator="['sixOrgCode']" :disabled="true" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label='所属七级机构' v-bind="formItemLayout">
            <a-input v-decorator="['sevenOrgCode']" :disabled="true" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 4rem !important">
        <a-col :md="12" :sm="24">
          <a-form-item label='上级机构' style="margin-bottom: 2rem" v-bind="formItemLayout">
            <!-- <a-tree :key="orgTreeKey" @select="handleCheck" @expand="handleExpand" :expandedKeys="expandedKeys"
              :treeData="orgTreeData" :selectedKeys="checkedKeys">
            </a-tree> -->
            <a-tree :key="orgTreeKey" :multiple="false" :checkable="true" :checkStrictly="true"
              :defaultCheckedKeys="defaultCheckedKeys[0]" @check="handleCheck" @expand="handleExpand"
              :expandedKeys="expandedKeys" :treeData="orgTreeData">
            </a-tree>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-bootom-button">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-org slot="overlay">
          <a-org-item key="1" @click="expandAll">展开所有</a-org-item>
          <a-org-item key="2" @click="closeAll">合并所有</a-org-item>
        </a-org>
        <a-button>
          树操作
          <a-icon type="up" />
        </a-button>
      </a-dropdown>
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
    <!--    <icons
      @choose="handleIconChoose"
      @close="handleIconCancel"
      :iconChooseVisible="iconChooseVisible">
    </icons>-->
  </a-modal>
</template>
<script>
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'OrgEdit',
  // components: {Icons},
  props: {
    orgEditVisiable: {
      default: false
    },
    orgInstId: ''
  },
  data() {
    return {
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      validateStatus: '',
      help: '',
      orgTreeKey: +new Date(),
      org: {
        icon: ''
      },
      checkedKeys: [],
      allTreeKeys: [],
      expandedKeys: [],
      orgTreeData: [],
      idToOrgCodeData: [],
      defaultCheckedKeys: [],
      iconChooseVisible: false,
      orgDataList: [],
      orgDataTree: {},//选中机构的数据
    }
  },
  computed: {
    show: {
      get: function () {
        return this.orgEditVisiable
      },
      set: function () {
      }
    }
  },
  methods: {
    reset() {
      this.loading = false
      this.orgTreeKey = +new Date()
      this.expandedKeys = this.checkedKeys = this.defaultCheckedKeys = []
      this.orgDataList = []
      this.org = {}
      this.form.resetFields()
    },
    onClose() {
      this.reset()
      this.$emit('close')
    },
    handleOrglevelChange(value) {
      //清空已选的上级机构
      this.checkedKeys = [];
    },
    handleCheck(selectedKeys) {
      let selectedKey = selectedKeys[0];
      let org = this.form.getFieldsValue();
      if (org.id == selectedKey) {
        this.$message.error('不能选择自己作为上级机构')
        return
      }
      for (let i = 0; i < this.orgDataList.length; i++) {
        let orgDataMap = this.orgDataList[i];
        if (orgDataMap.id == selectedKey) {
          let selectedOrgData = orgDataMap.orgData;
          if (parseInt(org.orgLevel) < parseInt(selectedOrgData.orgLevel)) {
            this.$message.error('不能选择机构级别低于自己的机构作为上级机构')
            return
          }
        }
      }
      this.checkedKeys = selectedKeys
    },
    expandAll() {
      this.expandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeys = []
    },
    handleExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    getOrgDataList(treeData) {
      //将机构树组装成以下结构：
      let orgDataMap = {
        id: "",
        orgData: ""
      }
      for (let i = 0; i < treeData.length; i++) {
        let orgData = treeData[i];
        orgDataMap.id = orgData.id;
        orgDataMap.orgData = orgData;
        this.orgDataList.push(orgDataMap);
        if (orgData.hasChildren) {
          this.getOrgDataList(orgData.children);
        }
      }
    },
    /*chooseIcons () {
      this.iconChooseVisible = true
    },
    handleIconCancel () {
      this.iconChooseVisible = false
    },
    handleIconChoose (value) {
      this.org.icon = value
      this.iconChooseVisible = false
    },
    deleteIcons () {
      this.org.icon = ''
    },*/

    setFormValues({ ...org }) {
      console.log("setFormValues");
      this.$get('admin/upmporg', {
        instId: org.instId,
        orgType: org.orgType,
        orgType: org.orgStatus
      }).then((r) => {
        console.log(r);
        // this.orgTreeData = r.data.rows.children
        this.defaultCheckedKeys.splice(0, this.defaultCheckedKeys.length, r.data.ids)
        this.checkedKeys = r.data.ids
        this.expandedKeys = r.data.ids
        this.allTreeKeys = r.data.ids
        this.idToOrgCodeData = r.data.idToCode
        this.orgTreeKey = +new Date();

        this.getOrgDataList(this.orgTreeData);
        let fields = ['id', 'instId', 'orgType', 'orgCode', 'orgName', 'bankBranchCode', 'innerBankCode',
          'contactName', 'orgLevel', 'contactAddress', 'contactFax', 'contactMail', 'contactPhone'
          , 'contactZipCode', 'orgStatus', 'crtOrgId', 'oprId', 'createTime', 'lastOprId', 'lastUpdateTime',
          "firstOrgCode", "secondOrgCode", "threeOrgCode", "fourOrgCode", "fiveOrgCode", "sixOrgCode", "sevenOrgCode"]
        Object.keys(org).forEach((key) => {
          if (fields.indexOf(key) !== -1) {
            this.form.getFieldDecorator(key)
            let obj = {}
            obj[key] = org[key]
            this.form.setFieldsValue(obj)
            console.log(obj, 111111111);
          }
        })
        if (org.parentId !== '0') {
          this.defaultCheckedKeys.push(org.parentId)
          this.checkedKeys = this.defaultCheckedKeys
          this.expandedKeys = this.checkedKeys
        }
        this.org.id = org.id
        this.orgTreeKey = +new Date()
      })

    },
    handleSubmit() {
      let checkedArr = this.checkedKeys
      if (checkedArr.length > 1) {
        this.$message.error('最多只能选择一个上级机构，请修改')
        return
      }
      if (checkedArr[0] === this.org.id) {
        this.$message.error('不能选择自己作为上级机构，请修改')
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          let icon = this.org.icon
          let org = this.form.getFieldsValue()
          org.icon = icon
          org.id = this.org.id
          if (checkedArr.length) {
            org.parentId = checkedArr[0]
            org.parentOrgCode = this.idToOrgCodeData[org.parentId];
          } else {
            if (org.orgLevel != "00") {
              this.$message.error('请选择上级机构')
              return
            }
            org.parentId = ''
          }
          org.instId = this.orgInstId;
          this.$put('admin/upmporg', {
            ...org
          }).then(() => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  },
  watch: {
    orgEditVisiable() {
      if (this.orgEditVisiable) {
        console.log("orgEditVisiable");
        this.$get('admin/upmporg', {
          type: '0'
        }).then((r) => {
          this.orgTreeData = r.data.rows.children
          this.allTreeKeys = r.data.ids
          this.idToOrgCodeData = r.data.idToCode
          this.orgTreeKey = +new Date()

        })
      }
    }
  }
}
</script>
